package com.lwm.web.interceptor;

import com.lwm.web.bean.ShopCartExample;
import com.lwm.web.common.Constants;
import com.lwm.web.controller.vo.UserVO;
import com.lwm.web.dao.ShopCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * @date 2020/1/5
 */
@Component
public class ShopCartNumberInterceptor implements HandlerInterceptor {
    @Autowired
    private ShopCartMapper shopCartMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if (null != request.getSession() && null != request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY)) {
            //如果当前为登陆状态，就查询数据库并设置购物车中的数量值
            UserVO userVO = (UserVO) request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY);
            //设置购物车中的数量
            ShopCartExample shopCartExample = new ShopCartExample();
            shopCartExample.createCriteria().andUserIdEqualTo(userVO.getId());
            userVO.setShopcartitemcount(shopCartMapper.countByExample(shopCartExample));
            request.getSession().setAttribute(Constants.MALL_USER_SESSION_KEY, userVO);

        }
        return true;  //购物车中的数量会更改，但是在这些接口中并没有对session中的数据做修改，这里统一处理一下
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
